package com.rxz.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rxz.dao.UserDao;
import com.rxz.entity.Result;
import com.rxz.entity.Users;
import com.rxz.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserLoginServiceImpl extends ServiceImpl<UserDao, Users> {

    @Resource
    private RedisTemplate redisTemplate;


    public Result login(Users param) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",param.getUsername());
        wrapper.eq("password",param.getPassword());
        Users user = getOne(wrapper);

        if(user == null){
            return ResultUtil.error(401,"用户不存在！");
        }

        // 登录成功，将用户信息写入redis
        String key = "user:"+ UUID.randomUUID()+"rxz";
        user.setPassword(null);
        redisTemplate.opsForValue().set(key,user,60L, TimeUnit.MINUTES);
        Map<String,Object> data = new HashMap<>();
        data.put("token", key);

        return ResultUtil.success(data);
    }
    public Result getUserInfoByToken(String token) {
// 通过token从redis中获取登录用户信息
        Object obj = redisTemplate.opsForValue().get(token);
        if(obj == null){
            return ResultUtil.error(401,"登录凭证无效，请重新登录");
        }
        log.debug("--------> obj: " + obj);
        log.debug("--------> obj to json: " + JSON.toJSONString(obj));
        Users user = JSON.parseObject(JSON.toJSONString(obj), Users.class);

        Map<String,Object> data = new HashMap<>();
        data.put("username", user.getUsername());
        data.put("phoneNumber",user.getPhoneNumber());
        data.put("name",user.getUsername());
        data.put("password", Arrays.toString(user.getPassword().split(String.valueOf(3))) + "***");

        return ResultUtil.success(data);
    }
    public void logout(String token) {
        redisTemplate.delete(token);
    }
}
